import { IRequestConfig, IApiControl, InterceptorsConfig, IResponse, IResolve, IRequestHook } from '../core/BaseInterface'
import CodeEnum from './CodeEnum'

// 请求拦截器
const interceptors: InterceptorsConfig = {
    request: function (options: IRequestConfig, apiControl: IApiControl): IRequestHook {
        // 示例1：为请求统一添加一些参数
        if (options.headers) {
            options.headers.commonData = '123456'
        } else {
            options.headers = { commonData: '123456' }
        }
        // 示例2：没有 token 直接返回登录页
        if (apiControl.auth && (!options.headers || !options.headers.token)) {
            return { type: false, message: '没有 token' }
        }

        return { type: true, message: 'ok' }
    },
    response: function (response: IResponse, options: IRequestConfig, apiControl: IApiControl): Promise<any> | IResolve {
        if (response.status !== 200) {
            return Promise.reject(response)
        }
        const res = response.data
        const code = res.code
        let codeMsg = CodeEnum.find(item => item.code == code)
        let message = codeMsg ? codeMsg.message : (res.message || '请求失败')
        // 示例：判断 code 然后返回 data
        if (res.code === 0) {
            return { data: res.data }
        } else {
            return Promise.reject(message)
        }
    }
}

export default interceptors